package com.jsgt.greekfire.ui.mine.user.backupwalletword

import android.annotation.SuppressLint
import android.content.ClipData
import android.content.ClipboardManager
import android.content.Context
import android.content.Intent
import androidx.lifecycle.Observer
import androidx.lifecycle.ViewModelProvider
import com.fhx.core.utils.ToastUtils
import com.jsgt.greekfire.BuildConfig
import com.jsgt.greekfire.R
import com.jsgt.greekfire.base.BaseBackgroundActivity
import com.jsgt.greekfire.ui.mine.user.backupwalletword.adapter.WordHelperAdapter
import com.jsgt.greekfire.dao.viewmodel.WalletViewModel
import kotlinx.android.synthetic.main.activity_backup_wallet_words.*
import org.web3j.utils.Numeric
import java.math.BigInteger

/**
 * 备份钱包
 */
class BackUpWalletWordActivity : BaseBackgroundActivity() {
    private val walletViewModel: WalletViewModel by lazy {
        ViewModelProvider(this).get(WalletViewModel::class.java)
    }
    private var identityId = -1

    override fun getLayoutId(): Int = R.layout.activity_backup_wallet_words

    companion object {
        fun start(context: Context) {
            val intent = Intent(context, BackUpWalletWordActivity::class.java)
            context.startActivity(intent)
        }
    }

    @SuppressLint("SetTextI18n")
    override fun main() {
//        window.addFlags(WindowManager.LayoutParams.FLAG_SECURE)//防止截屏

        identityId = intent.getIntExtra("identityId", -1)
        if (identityId == -1) {
            finish()
        }
        val wordHelperAdapter = WordHelperAdapter()
        words_rv.adapter = wordHelperAdapter

        copy_tv.setOnClickListener {
            //获取剪贴板管理器：
            val cm = getSystemService(Context.CLIPBOARD_SERVICE) as ClipboardManager
            val mClipData = ClipData.newPlainText("Label", private_key_tv.text.toString())
            cm.setPrimaryClip(mClipData)
            ToastUtils.show(R.string.copy_success)
        }

        back.setOnClickListener {
            onBackPressed()
        }

        walletViewModel.getIdentity(identityId)?.observe(this, Observer {
            if (it != null) {
                val words = it.getMnemonicByAES().split(" ") as ArrayList<String>
                wordHelperAdapter.addData(words)

                private_key_tv.text = Numeric.toHexStringNoPrefix(BigInteger(it.getPriKeyByAES()))
            }
        })
    }

    override fun onBackPressed() {
        super.onBackPressed()
        overridePendingTransition(R.anim.fade_in, R.anim.fade_out)
    }
}